package dict_service

import (
	"gorm.io/gorm"
	dd "pear-admin-layui-go/app/sys/dict/domain"
	fd "pear-admin-layui-go/framework/database"
)

func Enable(der *dd.DictEnableRequest) *gorm.DB {
	d := fd.Db.Model(dd.Dict{Id: der.Id}).Select("enable", "update_time", "update_by", "update_name").Updates(dd.Dict{
		Enable:     der.Enable,
		UpdateTime: der.UpdateTime,
		UpdateBy:   der.UpdateBy,
		UpdateName: der.UpdateName,
	})
	return d
}

func Save(dsr *dd.DictSaveRequest) (dd.Dict, error) {
	d := dd.Dict{
		TypeName:   dsr.TypeName,
		TypeCode:   dsr.TypeCode,
		Remark:     dsr.Remark,
		CreateTime: dsr.CreateTime,
		CreateBy:   dsr.CreateBy,
		CreateName: dsr.CreateName,
		Enable:     true,
		DelFlag:    false,
	}
	result := fd.Db.Create(&d)
	return d, result.Error
}

func Edit(der *dd.DictEditRequest) *gorm.DB {
	d := fd.Db.Model(dd.Dict{Id: der.Id}).Updates(dd.Dict{
		TypeName:   der.TypeName,
		TypeCode:   der.TypeCode,
		Remark:     der.Remark,
		UpdateBy:   der.UpdateBy,
		UpdateName: der.UpdateName,
		UpdateTime: der.UpdateTime,
	})
	return d
}

func EditPage(id int64) dd.Dict {
	var d dd.Dict
	fd.Db.Select("id", "type_name", "type_code", "remark").First(&d, id)
	return d
}

func Table(dsr *dd.DictSearchRequest) ([]dd.Dict, int64) {
	var count int64
	db := fd.Db.Model(dd.Dict{}).Where("del_flag = false")
	if dsr.TypeName != "" {
		db.Where("type_name like ?", "%"+dsr.TypeName+"%")
	}
	db.Count(&count)
	db.Select("id", "type_name", "type_code", "enable", "remark", "create_time", "create_name", "update_time", "update_name")
	var dicts []dd.Dict
	db.Limit(dsr.Limit).Offset((dsr.Page - 1) * dsr.Limit).Find(&dicts)
	return dicts, count
}
